/**
 * 处理数据库数据的操作
 */
const models = require('../models/init-models')
class LocationService {
  // 添加书本位置
  async createBookLocation(location_id, book_id, shelf_number, aisle_number) {
    // 写入数据库
    const res = await models.lib_book_locations.create({
      // 表的字段
      location_id,
      book_id,
      shelf_number,
      aisle_number
    })
    return res
  }

  // 修改书本位置
  async updateBookLocation(book_id, shelf_number, aisle_number) {
    try {
      const res = await models.lib_book_locations.update(
        {
          shelf_number,
          aisle_number
        },
        {
          where:
            { book_id }
        }
      );
      return res;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  // 获取书本位置
  async getBookLocation(book_id) {
    try {
      const bookLocation = await models.lib_book_locations.findAll({
        attributes: ['location_id', 'book_id', 'shelf_number', 'aisle_number'],
        include: [{ model: models.lib_books, as: 'book', attributes: ['title'] }],
        where: { book_id },
      });

      return bookLocation ? bookLocation : null
    } catch (error) {
      console.error(error);
      throw new Error('获取书本位置失败');
    }
  }

}

module.exports = new LocationService()
